import { useEffect, useState, useRef } from "react";
import to from "await-to-js";
import { getMockData as getMockDataApi } from "../../service/api/test";

const View = () => {
  // 钩子函数
  useEffect(() => {
    // 执行方法拿到数据
    getMockData();
    const myDiv = document.getElementById("myDiv");
    myDiv.addEventListener("scroll", function () {
      if (myDiv.scrollTop + myDiv.clientHeight >= myDiv.scrollHeight) {
        // 滚动到底部，执行你的操作
        console.log("已滚动到底部");
        // 往后查询五条
        pageNum.current = pageNum.current + 1;
        getMockData();
      }
    });
  }, []);
  // 定义变量
  const [listData, setListData] = useState([]);
  const pageSize = useRef(5);
  const pageNum = useRef(1);
  const backData = useRef([]);
  // 这里才能拿到最终的listData
  useEffect(() => {
    // 将最新的listData存在backData中
    backData.current = listData;
    console.log(listData, backData.current);
  }, [listData]);
  // 发送请求获取数据
  const getMockData = async () => {
    const [err, res] = await to(getMockDataApi(pageSize.current, pageNum.current));
    if (!err) {
      // 如果成功
      console.log(res.data);
      if (backData.current.length === 0) {
        setListData(res.data);
      } else {
        setListData([...backData.current, ...res.data]);
      }
    } else {
      // 如果失败
      console.log("请求数据失败了！！！");
    }
  };

  return (
    <>
      <div
        id="myDiv"
        style={{ height: "400px", width: "200px", border: "5px solid skyblue", overflow: "scroll", margin: "auto" }}>
        {listData.map((item) => {
          return (
            <div key={item.id} style={{ height: "100px", width: "200px", borderBottom: "1px solid #999" }}>
              <div>这是数据{item.id}</div>
              <div>标题：{item.title}</div>
              <div>作者：{item.author}</div>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default View;
